package com.mck.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Map;
import java.util.UUID;


public class JwtUtil {

    private static final String secretKey = "mySecretKeyMustBeAtLeast32BytesLong123!!";
    private static final SecretKey KEY = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
    private static final long EXPIRATION_TIME =  72 * 60 * 60 * 1000; // 3天

    /**
     * 生成JWT
     */
    public static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .claims(claims) // 添加自定义声明
                .expiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))  // 设置过期时间（毫秒）
                .issuedAt(new Date()) // 设置签发时间(当前)
                .signWith(KEY) // 添加密钥
                .id(UUID.randomUUID().toString()) // 添加JWT ID
                .compact();
    }

    /**
     * 解析JWT
     */
    public static Jws<Claims> parseToken(String token) {
        return Jwts.parser()
                .verifyWith(KEY) // 验证密钥
                .build() // 构建JwtParser
                .parseSignedClaims(token); // 解析JWT
    }
}